package com.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.Application;
import com.app.R;
import com.app.constant.Constants;
import com.app.http.HttpDataLoader;
import com.app.http.HttpDataReqUrl;
import com.app.model.bean.Bike;
import com.app.model.request.BikeReq;
import com.app.model.response.ResObj;
import com.app.utils.AnimationUtil;
import com.app.utils.DensityUtil;
import com.app.utils.LoginUtil;
import com.app.utils.StringUtil;
import com.app.utils.ToastUtil;
import com.app.view.MenuPopWindow;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActivityGetPwd extends ActivityBaseMenuImage {

    private static final String LOG_TAG = ActivityGetPwd.class.getSimpleName();
    @BindView(R.id.etContent)
    EditText etContent;
    @BindView(R.id.tvSubmit)
    TextView tvSubmit;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.tv4)
    TextView tv4;
    @BindView(R.id.tvWrong)
    TextView tvWrong;
    @BindView(R.id.tvShare)
    TextView tvShare;
    @BindView(R.id.llPwd)
    LinearLayout llPwd;
    @BindView(R.id.tvResult)
    TextView tvResult;
    @BindView(R.id.tvShare1)
    TextView tvShare1;
    @BindView(R.id.tvShare0)
    TextView tvShare0;
    @BindView(R.id.rlStart)
    RelativeLayout rlStart;
    @BindView(R.id.tvNumResult)
    TextView tvNumResult;
    @BindView(R.id.llResult)
    LinearLayout llResult;

    private HttpDataLoader dataLoader;

    private Bike bike;

    private long exitTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_pwd);
        ButterKnife.bind(this);
        dataLoader = new HttpDataLoader(this);
        setTitle("查询解锁码");
        int padding = DensityUtil.dip2px(8);
        setIvBackPadding(padding, padding, padding, padding);
        setIvBackImageRes(R.mipmap.icon_user);
        setIvBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ActivityGetPwd.this, ActivityMine.class));
//                overridePendingTransition(R.anim.push_left_in, 0);
            }
        });
        setMenuImage(R.mipmap.icon_share_black);
        setOnMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MenuPopWindow popWindow = new MenuPopWindow(ActivityGetPwd.this);
                popWindow.showPopupWindow(ActivityGetPwd.this.getHeadView().findViewById(R.id.ivMenu));
            }
//                ShareBoardConfig config = new ShareBoardConfig();
//                config.setShareboardPostion(ShareBoardConfig.SHAREBOARD_POSITION_CENTER);
//                config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR); // 圆角背景
////                config.setTitleVisibility(false); // 隐藏title
////                config.setCancelButtonVisibility(false); // 隐藏取消按钮
//                ((MainActivity)activity).shareAction.open(config);
//
//                MobclickAgent.onEvent(activity, "share");
//            }
        });

        /**
         * 缩小编辑框隐藏字体大小
         */
        SpannableString ss = new SpannableString("输入车辆编号");//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(20, true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        etContent.setHint(new SpannedString(ss));
//        setMenuText("查询");
//        setOnMenuClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (etContent.getText() == null || etContent.getText().length() < 1) {
//                    ToastUtil.getInstance().showToast(ActivityGetPwd.this, "车辆编号不能为空，请重新输入");
//                } else {
//                    getPwd();
//                }
//            }
//        });
    }

    private void init(Bike bike) {
        llResult.setVisibility(View.GONE);
        rlStart.setVisibility(View.GONE);
        llPwd.setVisibility(View.VISIBLE);
        if (bike == null) return;
        if (StringUtil.isEmpty(bike.getNum())) return;
        tvNum.setText("No." + bike.getNum() + " 解锁码：");
        String pwd = bike.getPwd();
        if (StringUtil.isEmpty(pwd)) return;
        tv1.setText(String.valueOf(pwd.charAt(0)));
        tv2.setText(String.valueOf(pwd.charAt(1)));
        tv3.setText(String.valueOf(pwd.charAt(2)));
        tv4.setText(String.valueOf(pwd.charAt(3)));
        llPwd.startAnimation(AnimationUtil.fromBottomToView());

    }

    private void getPwd() {
        if (StringUtil.isEmpty(etContent.getText().toString())) {
            ToastUtil.getInstance().showToast(this, "请输入车辆编号！");
            return;
        }
        if (!LoginUtil.isLogin()) {
//            startActivity(new Intent(this, ActivityLogin.class));
            showLoginDialog();
            return;
        }
        BikeReq req = new BikeReq();
        Bike bike = new Bike();
        bike.setNum(etContent.getText().toString());
        req.setBike(bike);
        dataLoader.POST(HttpDataReqUrl.URL_GET_PWD, req);
        Map<String, String> map_value = new HashMap<String, String>();
        map_value.put("车辆编号", etContent.getText().toString());
        MobclickAgent.onEventValue(Application.instance, "getPwd", map_value, 1);
    }

    private void wrongPwd() {
        if (StringUtil.isEmpty(etContent.getText().toString())) {
            ToastUtil.getInstance().showToast(this, "请输入车辆编号！");
            return;
        }
        if (!LoginUtil.isLogin()) {
//            startActivity(new Intent(this, ActivityLogin.class));
            showLoginDialog();
            return;
        }
        BikeReq req = new BikeReq();
        Bike bike = new Bike();
        bike.setNum(etContent.getText().toString());
        req.setBike(bike);
        dataLoader.POST(HttpDataReqUrl.URL_WRONG_PWD, req);
        Map<String, String> map_value = new HashMap<String, String>();
        map_value.put("车辆编号", etContent.getText().toString());
        MobclickAgent.onEventValue(Application.instance, "wrongPwd", map_value, 1);
    }

    private void showLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ActivityGetPwd.this);
        builder.setMessage("您尚未登录，请先登录！");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(ActivityGetPwd.this, ActivityLogin.class));

            }
        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
        builder.create().show();
    }


    @Override
    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
        Log.e(LOG_TAG, "onRequestSuccess");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "result: " + result);
        if (url.equals(HttpDataReqUrl.URL_GET_PWD)) {
            if (result.getCode() == Constants.CODE_SUCCESS) {
                if (result.getData() instanceof Bike) {
                    bike = (Bike) result.getData();
                    init(bike);
                    if (bike != null) {
                        Map<String, String> map_value = new HashMap<String, String>();
                        map_value.put("车辆编号", bike.getNum());
                        map_value.put("车辆密码", bike.getPwd());
                        MobclickAgent.onEventValue(Application.instance, "getPwdResult", map_value, 1);
                    }
                }
//                ToastUtil.getInstance().showToast(ActivityGetPwd.this, result.getMsg());
            } else {
//                ToastUtil.getInstance().showToast(ActivityGetPwd.this, result.getMsg());
                rlStart.setVisibility(View.GONE);
                llPwd.setVisibility(View.GONE);
                llResult.setVisibility(View.VISIBLE);
                tvNumResult.setText("No." + etContent.getText().toString() + "解锁码：");
                llResult.startAnimation(AnimationUtil.fromBottomToView());
                Map<String, String> map_value = new HashMap<String, String>();
                map_value.put("车辆编号", etContent.getText().toString());
                map_value.put("失败原因", result.getMsg());
                MobclickAgent.onEventValue(Application.instance, "getPwdResult", map_value, 0);

            }
        }
        if (url.equals(HttpDataReqUrl.URL_WRONG_PWD)) {
            ToastUtil.getInstance().showToast(ActivityGetPwd.this, result.getMsg());
        }


    }

    @Override
    public void onRequestError(String url, int statusCode, String error) {
        Log.e(LOG_TAG, "onRequestError");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "statusCode: " + statusCode);
        Log.e(LOG_TAG, "error: " + error);
        ToastUtil.getInstance().showToast(ActivityGetPwd.this, error);
    }

    @OnClick({R.id.tvSubmit, R.id.tvWrong, R.id.tvShare, R.id.tvShare1, R.id.tvShare0})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSubmit:
                getPwd();
                break;
            case R.id.tvWrong:
                wrongPwd();
                break;
            case R.id.tvShare:
                Intent intent = new Intent(ActivityGetPwd.this, ActivitySharePwd.class);
                startActivity(intent);
                break;
            case R.id.tvShare0:
                Intent intent0 = new Intent(ActivityGetPwd.this, ActivitySharePwd.class);
                startActivity(intent0);
                break;
            case R.id.tvShare1:
                Intent intent1 = new Intent(ActivityGetPwd.this, ActivitySharePwd.class);
                startActivity(intent1);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.getInstance().showToast(this, "再按一次退出程序", Toast.LENGTH_SHORT);
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }

    }
}
